import { BrowserWindow, app,Menu } from 'electron';
import { MainWindowPath } from '../projectPath';
import path from 'node:path';
import fs from 'fs'
let mainWindow: Electron.BrowserWindow | null;

export const App = {
    initMainWindow() {
		Menu.setApplicationMenu(null) // 去掉菜单栏
        mainWindow = new BrowserWindow({
            width: 800,
            height: 600,
			minWidth: 960,
			minHeight: 600,
			show: false,
			frame: false,
            webPreferences: {
                nodeIntegration: true,
                contextIsolation: true,
                backgroundThrottling: false,
                preload: path.join(__dirname, 'preload.js')
            },
        });
        // mainWindow.setMenu(null);
		// Menu.setApplicationMenu(null) // 去掉菜单栏
        mainWindow.center();
		// 设置窗口的坐标
		
		// 设置窗口标题栏的图标
		mainWindow.setIcon(path.join(__dirname, 'static','icon.ico'));

        mainWindow.on('focus',() => {
			
        })

        mainWindow.on('blur',() => {

        })

        mainWindow.once("ready-to-show", () => {
          if (process.argv.indexOf("--openAsHidden") < 0) 
              mainWindow.show();
        });

        mainWindow.on("close", (event) => {
        	if(!global.isClose){
        		// 阻止默认的关闭操作
        		event.preventDefault();
        		mainWindow.minimize();
        		mainWindow.hide();
        	}
        })
		
		mainWindow.webContents.session.addListener('will-download',(evt,item,webContents) =>{
			const fileName = item.getFilename();
			const url = item.getURL();
			const startTime = item.getStartTime();
			const initialState = item.getState();
			const downloadPath = app.getPath('downloads');
		
			let fileNum = 0;
			
			  // 通知渲染进程，有一个新的下载任务
			mainWindow.webContents.send('new-download-item', {
			  url,
			  startTime,
			  state: initialState,
			  paused: item.isPaused(),
			  totalBytes: item.getTotalBytes(),
			  receivedBytes: item.getReceivedBytes(),
			});
		
			// 下载任务更新
			item.on('updated', (e, state) => { // eslint-disable-line
			  mainWindow.webContents.send('download-item-updated', {
				startTime,
				state,
				totalBytes: item.getTotalBytes(),
				receivedBytes: item.getReceivedBytes(),
				paused: item.isPaused(),
			  });
			});
			// 下载任务完成
			item.on('done', (e, state) => { // eslint-disable-line
			  mainWindow.webContents.send('download-item-done', {
				startTime,
				state,
			  });
			});
		})
    },
    loadMainWindow() {
        mainWindow?.loadURL(MainWindowPath);
    },
    showDevTools() {
        mainWindow?.webContents.openDevTools();
    },
    getMainWindow() {
        return mainWindow;
    },
	dragMainwindow(coordinates){
		mainWindow.setBounds({ x: coordinates.x, y: coordinates.y,width:800,height:600});
	}
}